from django.shortcuts import render
from django.views.generic import ListView
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import *


import datetime
import logging
logging.basicConfig(level=logging.NOTSET)


# Create your views here.
class ToAllProducts(ListView):
    """
    所有商品，每类商品推送10个
    :param request:
    :return:
    """
    def __init__(self):
        super(ToAllProducts, self).__init__()
        self.model = Product
        self.template_name = 'comet/all_products.html'
        self.context_object_name = 'all_overview_products'
        self.all_overview_products = []

    def to_all_products(self, request):
        self.all_overview_products.clear()
        try:
            all_products_type = ProductType.objects.all()
            for pt in all_products_type:
                overview_products = self.model.objects.filter(product_type=pt.type_id).all()[:10]
                for overview_product in overview_products:
                    self.all_overview_products.append(overview_product)
        except:
            return render(request, '500.html')

        return self.all_overview_products


class ToTypeProducts(ListView):
    """
    所有商品-》更多，跳转该类所有商品
    :param request:
    :return:
    """
    def __init__(self):
        super(ToTypeProducts, self).__init__()
        self.model = Product
        self.template_name = 'comet/filter_products.html'
        self.context_object_name = ['product_type',
                                    'type_products']

    def to_type_products(self, request):
        p_type = request.GET.get('p_type')
        if p_type and p_type != '':
            try:
                type_products = self.model.objects.filter(product_type=p_type).all()
                product_type = ProductType.objects.filter(type_id=p_type).all()[0]
            except:
                return render(request, '500.html')

            return render(request, self.template_name, {self.context_object_name[0]: product_type,
                                                        self.context_object_name[1]: type_products})
        else:
            return render(request, self.template_name, None)


class ToSearchProducts(ListView):
    """
    所有商品-》搜索商品结果
    :param request:
    :return:
    """
    def __init__(self):
        super(ToSearchProducts, self).__init__()
        self.model = Product
        self.template_name = 'comet/filter_products.html'
        self.context_object_name = ['filter_args',
                                    'type_products']

    def to_search_products(self, request):
        p_name = request.POST.get('p_name')
        p_type = request.POST.get('p_type')
        p_price_start = request.POST.get('p_price_start')
        p_price_end = request.POST.get('p_price_end')

        if p_name and p_type and p_price_start and p_price_end:
            if p_name == '':
                if p_type == '':
                    if p_price_start == '':
                        if p_price_end == '':
                            sql = 'SELECT * FROM commet_product'
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_price < ' + p_price_end
                    else:
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_price > ' + p_price_start
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_price between ' + p_price_start + 'AND' + p_price_end
                else:
                    if p_price_start == '':
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_type = ' + p_type
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_type = ' + p_type + 'AND priduct_price < ' + p_price_end
                    else:
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_type = ' + p_type + 'AND priduct_price between ' + p_price_start
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_type = ' + p_type + 'AND priduct_price > ' + p_price_start + 'AND' + p_price_end
            else:
                if p_type == '':
                    if p_price_start == '':
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND priduct_price < ' + p_price_end
                    else:
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND priduct_price > ' + p_price_start
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'product_price between ' + p_price_start + 'AND' + p_price_end
                else:
                    if p_price_start == '':
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND product_type = ' + p_type
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND product_type = ' + p_type + 'AND priduct_price < ' + p_price_end
                    else:
                        if p_price_end == '':
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND product_type = ' + p_type + 'AND priduct_price > ' + p_price_start
                        else:
                            sql = 'SELECT * FROM comet_product WHERE product_name = ' + p_name + 'AND product_type = ' + p_type + 'product_price between ' + p_price_start + 'AND' + p_price_end

            try:
                search_products = Product.objects.raw(sql)
            except:
                return render(request, '500.html')
            filter_args = {'p_name': p_name,
                           'p_type': p_type,
                           'p_price_start': p_price_start,
                           'p_price_end': p_price_end}
            return render(request, self.template_name, {self.context_object_name[0]: filter_args,
                                                        self.context_object_name[1]: search_products})


class ToDetailProduct(ListView):
    """
    商品详情
    :param request:
    :return:
    """
    def __init__(self):
        super(ToDetailProduct, self).__init__()
        self.model = Product
        self.template_name = 'comet/detail_product.html'
        self.context_object_name = 'detail_product'

    def to_detail_product(self, request):
        p_id = request.GET.get('p_id')

        try:
            detail_product = self.model.objects.filter(product_id=p_id).all()[0]
            return render(request, self.template_name, {self.context_object_name: detail_product})
        except:
            return render(request, '500.html')


@csrf_exempt
def do_buy_now(request):
    """
    购买事件
    :param request:
    :return:
    """
    user_id = request.session.get('user_id')
    product_id = request.POST.get('p_id')
    product_discount = request.POST.get('product_discount')
    deal_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    try:
        Deal.objects.create(user_id=user_id, product_id=product_id, product_discount=product_discount, deal_timestamp=deal_timestamp)
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)


@csrf_exempt
def do_add_to_cart(request):
    """
    添加到购物车事件
    :param request:
    :return:
    """
    stu_id = request.session.get('stu_id')
    product_id = request.POST.get('p_id')
    product_discount = request.POST.get('product_discount')
    Cart.objects.create(user_id=stu_id, product_id=product_id, product_discount=product_discount)

    try:
        # Cart.objects.create(user_id=stu_id, product_id=product_id, product_discount=product_discount)
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)


class ToCart(ListView):
    """
    查看我的购物车事件
    :param request:
    :return:
    """
    def __init__(self):
        super(ToCart, self).__init__()
        self.model = [Cart, Product]
        self.template_name = 'comet/cart.html'
        self.context_object_name = 'cart_products'

    def to_cart(self, request):
        stu_id = request.session.get('stu_id')
        cart_products = []

        try:
            cart_products_record = Cart.objects.filter(user_id=stu_id).all()
            for cart_product in cart_products_record:
                cart_products.append(Product.objects.filter(product_id=cart_product.product_id).all())
        except:
            return render(request, '500.html')

        return render(request, self.template_name)


@csrf_exempt
def do_remove_cart_product(request):
    """
    删除购物车产品事件
    :param request:
    :return:
    """
    stu_id = request.session.get('stu_id')
    product_id = request.POST.get('p_id')

    try:
        Cart.objects.filter(user_id=stu_id, product_id=product_id).all().delete()
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)


@csrf_exempt
def do_buy_cart(request):
    """
    购物车购买事件
    :param request:
    :return:
    """
    stu_id = request.session.get('stu_id')
    deal_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        cp = Cart.objects.filter(user_id=stu_id).all()
        for p in cp:
            Deal.objects.create(user_id=user_id,
                                product_id=p.product_id,
                                product_discount=p.product_discount,
                                deal_timestamp=deal_timestamp)
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)


@csrf_exempt
def do_add_to_favorate(request):
    """
    添加到收藏夹事件
    :param request:
    :return:
    """
    stu_id = request.session.get('stu_id')
    product_id = request.POST.get('p_id')

    try:
        Favorite.objects.create(user_id=stu_id, product_id=product_id)
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)


@csrf_exempt
def do_remove_favorite_product(request):
    """
    删除收藏夹产品事件
    :param request:
    :return:
    """
    stu_id = request.session.get('stu_id')
    product_id = request.POST.get('p_id')

    try:
        Favorite.objects.filter(user_id=stu_id, product_id=product_id).all().delete()
        return JsonResponse(200, safe=False)
    except:
        return JsonResponse(500, safe=False)
